package com.tacademy.android.lbs.location.model;

import java.io.CharArrayWriter;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.xml.sax.Attributes;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.DefaultHandler;
import org.xml.sax.helpers.XMLReaderFactory;

public class PlaceParser extends DefaultHandler {
	private Place place;
	private List<Place> places;
	private CharArrayWriter contents = new CharArrayWriter();

	public List<Place> getPlaces() {
		return places;
	}

	public void startDocument() {
		places = new ArrayList<Place>();
	}

	public void startElement(String namespaceURI, String localName,
			String qName, Attributes attr) throws SAXException {
		if (localName.equals("place")) {
			place = new Place();
		}
		contents.reset();
	}

	public void endElement(String namespaceURI, String localName, String qName)
			throws SAXException {
		if (place == null) {
			return;
		}
		if (localName.equals("place")) {
			places.add(place);
		}
		if (localName.equals("placeName")) {
			place.setPlaceName(contents.toString());
		}
		if (localName.equals("placeId")) {
			place.setPlaceId(contents.toString());
		}
		if (localName.equals("latitude")) {
			try {
				place.setLatitude(Double.parseDouble(contents.toString()));
			} catch (NumberFormatException ne) {
				place.setLatitude(0.0);
			}
		}
		if (localName.equals("longitude")) {
			try {
				place.setLongitude(Double.parseDouble(contents.toString()));
			} catch (NumberFormatException ne) {
				place.setLongitude(0.0);
			}
		}
		if (localName.equals("user")) {
			place.setUser(contents.toString());
		}
		if (localName.equals("id")) {
			place.setPlaceId(contents.toString());
		}
	}

	public void characters(char[] ch, int start, int length)
			throws SAXException {
		contents.write(ch, start, length);
	}

	public List<Place> parse(Reader xmlReader) {
		try {
			// Create SAX 2 parser...
			XMLReader xr = XMLReaderFactory.createXMLReader();
			// Set the ContentHandler...
			PlaceParser parser = new PlaceParser();
			xr.setContentHandler(parser);
			// Parse the file...
			xr.parse(new InputSource(xmlReader));

			return parser.getPlaces();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return Collections.emptyList();
	}
}
